<?php

namespace Common\Model;

use Common\Lib\Upload\ImgManager;
use Think\Model;

class TagModel extends Model
{
    protected $_validate = array(
        array('tag', 'require', '标签必须填写！', 1),
    );

    protected $_auto = array(
        array('addtime', 'time', 1, 'function'),
    );

    /**
     * 获取列表
     *
     * @param string $map
     * @param bool   $page
     * @param string $sort
     * @param string $num
     * @param bool   $showcat
     * @return mixed
     */
    public function get_list($map = '', $page = false, $sort = '', $num = '', $showcat = false, $startrow = 0)
    {
        $limit = $num ? $num : 10;
        if ($page) {
            $count = $this->where($map)->count();
            $Page = pager($count, $limit);
            $limit = $Page->firstRow . ',' . $Page->listRows;
            $page_str = $Page->fshow();
        }else{
			$limit=$startrow . ',' . $limit;
		}
        if (empty($sort)) {
            $sort = 'sort DESC, count_question DESC';
        }

        $result = $this->where($map)->order($sort)->limit($limit)->select();
        foreach ($result as $key => $v) {
            $v['img'] = $this->get_tag_img($v['img'], $v['id']);
            $v['url'] = RU('tag/view', array('t' => $v['id']));
            $v['audit_str'] = $this->get_tag_audit($v['audit']);
            if ($showcat) {
                $cat = D('TagCat')->get_cat_one($v['cat']);
                $v['cat_str'] = $cat['title'];
            }
            $list[] = $v;
        }
        $return['list'] = $list;
        if ($page) {
            $return['count'] = $count;
        } else {
            $return['count'] = count($list);
        }
        $return['page'] = $page_str;
        //print_r($return);
        return $return;
    }

    /**
     * 获取标签
     *
     * @param string $id
     * @return mixed
     */
    public function get_one_id($id = '')
    {
        $map['id'] = intval($id);
        $info = $this->where($map)->find();
        if (!empty($info)) {
            $info['imgsrc'] = $this->get_tag_img($info['img'], $info['id']);
            $cat = D('TagCat')->get_cat_one($info['cat']);
            $info['cat_cn'] = $cat['title'];
        }
        return $info;
    }

    /**
     * 获取标签
     *
     * @param string $tag TAG 名称
     * @return array|null|bool
     */
    public function get_one_tag($tag = '')
    {
        $map['tag'] = trim($tag);
        $info = $this->where($map)->find();
        if (!empty($info)) {
            $info['imgsrc'] = $this->get_tag_img($info['img'], $info['id']);
        }
        return $info;
    }

    /**
     * 检测标签
     *
     * @param string $tag
     * @param string $id
     * @return bool
     */
    public function chenk_tag($tag = '', $id = '')
    {
        if (empty($tag)) {
            return false;
        }
        $map['tag'] = trim($tag);
        $info = $this->where($map)->find();
        if (!empty($info)) {
            if (!empty($id) && $info['id'] == $id) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取标签图标URL
     *
     * 如果 $img 为空，则以 TAG 图标 ID 末位数生成系统默认 TAG 图标
     *
     * @param string $img TAG图标名称
     * @param string $id  TAG图标ID
     * @return string
     */
    public function get_tag_img($img = '', $id = '')
    {
        if (empty($img)) {
            $img = __ROOT__ . '/' . C('YTATA_IMG_TAG_DIR') . substr($id, -1) . '.gif';
        } else {
            $img = ImgManager::make($img)->url();
        }
        return $img;
    }

    /**
     * 获取审核状态
     *
     * @param string $audit
     * @return string
     */
    public function get_tag_audit($audit = '0')
    {
        switch ($audit) {
            case '0':
                $audit_str = '<span style="color:#FF0000">未审核</span>';
                break;
            case '1':
                $audit_str = '<span style="color:#009900">已审核</span>';
                break;
            case '-1':
                $audit_str = '<span style="color:#999999">未通过</span>';
                break;
        }
        return $audit_str;
    }

    /**
     * 更新标签统计（从数据库统计）
     * @param string|array $tagid
     * @param string       $type
     */
    public function update_tag_count($tagid = '', $type = '1')
    {
        if (!is_array($tagid)) {
            $tagid = array($tagid);
        }
        foreach ($tagid as $v) {
            //更新标签问题总数
            if ($type == '1') {
                $where['tagid'] = intval($v);
                $data['count_question'] = M('QuestionTag')->where($where)->count();
                $data['id'] = intval($v);
                $this->save($data);
            }
            //更新标签文章总数
            if ($type == '2') {
                $where['tagid'] = intval($v);
                $data['count_article'] = M('ArticleTag')->where($where)->count();
                $data['id'] = intval($v);
                $this->save($data);
            }
            // 更新标签的主题统计
            if ($type == '3') {
                $where['tagid'] = intval($v);
                $data['count_bbs'] = M('BbsTag')->where($where)->count();
                $data['id'] = intval($v);
                $this->save($data);
            }
        }
    }

    /**
     * 更新标签统计（直接数据增减）
     *
     * @param array|int $tagid
     * @param string    $fieldname 更新字段名
     */
    public function set_tag_count($tagid, $fieldname = 'count_question')
    {
        if (!is_array($tagid)) {
            $tagid = array($tagid);
        }
        foreach ($tagid as $v) {
			if ($fieldname =='count_question'){
				$data['count_question']=M('QuestionTag')->where('tagid='.$v)->count();
			 	$this->where('id='.$v)->save($data);
			}
			if ($fieldname =='count_article'){
				$data['count_article']=M('ArticleTag')->where('tagid='.$v)->count();
			 	$this->where('id='.$v)->save($data);
			}
			if ($fieldname =='count_bbs'){
				$data['count_bbs']=M('BbsTag')->where('tagid='.$v)->count();
			 	$this->where('id='.$v)->save($data);
			}
        }
    }

    /**
     * 批量添加标签
     * 如果标签名称已存在，则不重复添加
     * @param array $tags
     * @return int[] 添加标签的ID列表
     */
    public function batch_add_tag(array $tags)
    {
        $ret_tagids = array();
        foreach ($tags as $tag) {
            $tag = trim($tag);
            $id = $this->where(array('tag' => $tag))->getField('id');
            if (!$id) {
                $data = compact('tag');
                $data = $this->create($data);
                if ($data) {
                    $ret_tagids[] = (int)$this->add();
                }
            } else {
                $ret_tagids[] = (int)$id;
            }
        }
        return $ret_tagids;
    }

    /**
     * 添加标签
     * @param $tagName
     * @return mixed
     */
    public function tag_add($tagName)
    {
        $tag = trim($tagName);
        if (!$this->create(compact('tag'))) {
            return false;
        }
        return $this->add();
    }

    /**
     * 获取标签名的ID [如果标签不存在则先注册标签，然后返回ID]
     * @param $tagName
     * @return int
     */
    public function get_tagid($tagName)
    {
        $tag = $this->get_one_tag($tagName);
        if (empty($tag)) {
            $tagid = $this->tag_add($tagName);
        } else {
            $tagid = $tag['id'];
        }
        return $tagid;
    }

    /**
     * 标签字段填充
     * @param array $tags
     * @return array
     */
    public function tags_fill($tags)
    {
        $tags = array_map(function ($tag) {
            $tag['tagurl'] = RU('tag/view', array('t' => $tag['tagid']));
            return $tag;
        }, $tags);
        return $tags;
    }
}